package eiisan.lucenedemo;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.FSDirectory;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

/**
 * @description:
 * 索引库的管理
 * 1、添加文档
 * 2、删除文档
 *  1)删除全部
 *  2)根据查询、关键词删除文档
 * 3、修改文档
 * 修改的，原理是先删除后添加
 *
 * @author: eii
 * @time: 2020/8/8 12:14 上午
 */
public class LuceneManager {

    private IndexWriter indexWriter;

    @Before
    public void init() throws IOException {
         indexWriter = new IndexWriter(FSDirectory.open(
                new File("/Users/eii/tmp/index").toPath()),
                new IndexWriterConfig(new IKAnalyzer()));
    }

    @Test
    public void addDocument() throws IOException {
        IndexWriter indexWriter = new IndexWriter(FSDirectory.open(
                new File("/Users/eii/tmp/index").toPath()),
                new IndexWriterConfig(new IKAnalyzer()));
        Document document = new Document();

        document.add(new TextField("name","新添加的文件", Field.Store.YES));
        document.add(new TextField("content","新添加的文件内容", Field.Store.YES));
        document.add(new StoredField("path","/Users/eii/doc"));
        indexWriter.addDocument(document);
        indexWriter.close();
    }

    /**
     * 删除全部文档
     * @throws IOException
     */
    @Test
    public void deleteAllDocument() throws IOException {
        //删除全部文档
        indexWriter.deleteAll();
        indexWriter.close();
    }

    /**
     * 删除查询出来的文档
     * @throws IOException
     */
    @Test
    public void deleteDocumentByQuery() throws IOException {
        //删除查询出来的文档
        indexWriter.deleteDocuments(new Term("name","apache"));
        indexWriter.close();
    }


    @Test
    public void updateDocument() throws IOException {
        //创建一个新的文档
        Document document = new Document();
        document.add(new TextField("name","更新之后的文档name", Field.Store.YES));
        document.add(new TextField("content","更新之后的文档content", Field.Store.YES));
        document.add(new StoredField("path","更新之后的文档path"));
        //更新操作（先删除查到的，在新增）
        indexWriter.updateDocument(new Term("name","spring"),document);
        indexWriter.close();
    }

}
